// ##############################
// ####  note:  bokeweilai uart main fun
// ####  create:  TANWENHUI (twh:谭文辉)
// ####  date:   2024/6/18
// ##############################

#include "bkwl_common.h"
#include "dev_log.h"
#include "dev_queue.h"
#include "bkwl_event.h"
#include "bkwl_uart.h"

// X:\twh\work\bk7258\bk_avdk\bk_idk\components\tfm\tfm\platform\ext\target\beken\armino\include\driver\hal\hal_uart_types.h
static uint32_t g_badurate = 0;

void bkwl_uart_init_callback(uart_id_t id, void *param)
{
	tprintf("uart2 callback..................\r\n");
}

bkwl_err_t bkwl_uart_init(int uart_id, uint32_t badurate)
{

	bkwl_err_t ret = BK_OK;
	uart_config_t config = {0};
	tprintf("bkwl_uart_init uart_id=%d,badurate=%d\n", uart_id, badurate);
	os_memset(&config, 0, sizeof(uart_config_t));

	g_badurate = badurate;
	config.baud_rate = badurate; // 9600;
	config.data_bits = UART_DATA_8_BITS;
	config.parity = UART_PARITY_NONE;
	config.stop_bits = UART_STOP_BITS_1;
	config.flow_ctrl = UART_FLOWCTRL_DISABLE;
	config.src_clk = UART_SCLK_XTAL_26M; // UART_SCLK_XTAL_26M; // UART_PARITY_NONE; // UART_SCLK_APLL; // UART_SCLK_XTAL_26M;

	// BK_LOG_ON_ERR(bk_uart_init(uart_id, &config));

	// const uart_config_t config =
	// 	{
	// 		.baud_rate = 9600,
	// 		.data_bits = UART_DATA_8_BITS,
	// 		.parity = UART_PARITY_NONE,
	// 		.stop_bits = UART_STOP_BITS_1,
	// 		.flow_ctrl = UART_FLOWCTRL_DISABLE,
	// 		.src_clk = UART_SCLK_XTAL_26M

	// 	};

	tprintf("doorbell_uart2_init  0\n");
	ret = bk_uart_init(uart_id, &config);
	if (ret != BK_OK)
	{
		bk_uart_deinit(uart_id);
		tprintf("uart2 INIT ERROR\r\n");
		return 1;
	}
	tprintf("doorbell_uart2_init  0 0\n");
	bk_uart_enable_rx_interrupt(uart_id);
	tprintf("doorbell_uart2_init  0 1\n");
	bk_uart_register_rx_isr(uart_id, bkwl_uart_init_callback, 0);

	tprintf("bkwl_uart_init 2\n");
	return ret;
}

bkwl_err_t bkwl_uart_write(int uart_id, uint8_t *send_data, uint32_t buf_len)
{
	bkwl_err_t ret = BK_OK;
	//	int uart_id = BKWL_IOT_DOORBELL_UART_ID; uart_write_byte(id, *string++);
	// tprintf("bkwl_uart_write badurate=%d\n", g_badurate);
	BK_LOG_ON_ERR(bk_uart_write_bytes(uart_id, send_data, buf_len));
	//  uart_write_byte(id, *string++);

	// for (uint32_t i = 0; i < buf_len; i++)
	// {
	// 	uart_write_byte(id, *send_data++);
	// }

	// tprintf("bkwl_uart_write uart_id=%d, data_len:%d\n", uart_id, buf_len);
	return ret;
}

uint32_t bkwl_uart_read(int uart_id, uint8_t *read_data, uint32_t buf_len)
{
	uint32_t ret = 0;
	//	int uart_id = BKWL_IOT_DOORBELL_UART_ID;
	tprintf("bkwl_uart_write read\n");
	ret = bk_uart_read_bytes(uart_id, read_data, buf_len, BEKEN_WAIT_FOREVER);
	tprintf("bkwl_uart_write exit\n");
	return ret;
}
bkwl_err_t bkwl_uart_close(int uart_id)
{
	bkwl_err_t ret = BK_OK;
	//	int uart_id = 2;
	BK_LOG_ON_ERR(bk_uart_deinit(uart_id));
	return ret;
}
